package cn.didi.feidi.androidorder.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.adapter.MainHomePageRecyclerViewAdapter;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.databinding.FragmentSearchGoodsBinding;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.WaterBucket;

/**
 * Created by jinxiong on 2017/8/25.
 */

public class SearchGoodsFragment extends FeidiBaseFragment {


    FragmentSearchGoodsBinding binding;

    MainHomePageRecyclerViewAdapter adapter;

    private boolean searching;


    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static SearchGoodsFragment newInstance(Bundle bundle) {
        SearchGoodsFragment fragment = new SearchGoodsFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new MainHomePageRecyclerViewAdapter(this);
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_search_goods, container, false);
        return binding.getRoot();
    }

    @Override
    protected void initViews(View rootView) {
        binding.searchGoodsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.searchGoodsRecyclerView.setAdapter(adapter);
        actionBarSetting();
        binding.searchGoodsSwipeRefreshLayout.setEnabled(false);
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void addListener() {
        binding.searchGoodsBackFl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        binding.searchGoodsClearTextIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.searchGoodsSearchEt.setText("");
            }
        });

        binding.searchGoodsSearchTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String searchMessage = binding.searchGoodsSearchEt.getText().toString().trim();
                if (searchMessage.length() == 0 || searching) {
                    return;
                }

                if (!binding.searchGoodsSwipeRefreshLayout.isRefreshing()) {
                    binding.searchGoodsSwipeRefreshLayout.setRefreshing(true);
                }

                searching = true;

                searchGoodsByName(searchMessage);

            }
        });


    }

    private void searchGoodsByName(String searchMessage) {

        HashMap<String, String> parameters = new HashMap<>();

        parameters.put("pageNum", "1");
        parameters.put("pageSize", "20");
        parameters.put("keyName", searchMessage);


        String url;

        if (!UserManager.isBingAccount()) {

            url = Api.GET_WATER_BUCKET_BY_NAME_NO_TOKEN;
        } else {
            parameters.put("userId", UserManager.getUserId());
            parameters.put("token", UserManager.getToken());
            url = Api.GET_WATER_BUCKET_BY_NAME;
        }

        executeRequest(new AppActionRequest<>(url, parameters,
                new TypeToken<ApiResponse<List<WaterBucket>>>() {
                }.getType(), new ActionCallbackListener<List<WaterBucket>>() {
            @Override
            public void onSuccess(String message, List<WaterBucket> data) {

                adapter.setWaterBuckets((ArrayList<WaterBucket>) data);

                if (searching) {
                    searching = false;
                }
                if (binding.searchGoodsSwipeRefreshLayout.isRefreshing()) {
                    binding.searchGoodsSwipeRefreshLayout.setRefreshing(false);
                }

            }

            @Override
            public void onFailure(int errorEvent, String message) {
                if (searching) {
                    searching = false;
                }
                if (binding.searchGoodsSwipeRefreshLayout.isRefreshing()) {
                    binding.searchGoodsSwipeRefreshLayout.setRefreshing(false);
                }
            }
        }));
    }


    public void actionBarSetting() {
        getFeidiActionBar().setVisibility(View.GONE);
    }
}
